package cn.bonoon.util;

import java.io.File;
import java.util.Collection;

import javax.servlet.ServletContext;

import cn.bonoon.kernel.util.StringHelper;

public class PathUtil {

	/** 主要用于url地址的路径分隔符，注意这里不是文件系统的分隔符 */
	public final static char separatorChar = '/';
	public final static String separatorString = Character.toString(separatorChar);

	public static String resolvePath(Object oPath){
		if(oPath instanceof Collection) return path(((Collection<?>)oPath).toArray());
		if(oPath.getClass().isArray()) return path((Object[])oPath);
		if(oPath instanceof File) return ((File) oPath).getPath();
		if(oPath instanceof ServletContext) return ((ServletContext) oPath).getContextPath();
		
		//都不是以上类型的，则直接认为对象就是"String"类型
		return oPath.toString();
	}
	
	public static String path(Object... oPaths){
		
		String str = "";
		for(Object oPath : oPaths){
			
			if(null == oPath) continue;
			
			str = combine(str, resolvePath(oPath));
		}
		return str;
	}
	
	public static String path(String root, String... ps){

		String str = root;
		
		for(int i = 0; i < ps.length; i++){
			str = combine(str, ps[i]);
		}
		
		return str;
	}
	
	private static String combine(String path1, String path2){
		if(StringHelper.isEmpty(path1)) return path2;
		if(StringHelper.isEmpty(path2)) return path1;
		
		boolean 
			endChecked = path1.endsWith(separatorString), 
			startChecked = path2.startsWith(separatorString);
		
		if(!endChecked && !startChecked){ return path1 + separatorChar + path2; }
		
		if(endChecked && startChecked){ return path1 + path2.substring(1); }
		
		return path1 + path2;
	}
	
	/** 判断该路径是否以{@value #separatorChar}结束，如果不是，则添加{@value #separatorChar}符号 */
	public static String endWithSeparator(String path){
		if(path.charAt(path.length() - 1) != separatorChar){
			return path + separatorChar;
		}
		return path;
	}
	
	/** 判断该路径是否以{@value #separatorChar}结束，如果是，则去掉{@value #separatorChar}符号 */
	public static String notEndWithSeparator(String path){
		if(path.charAt(path.length() - 1) == separatorChar){
			return path.substring(0, path.length() - 1);
		}
		return path;
	}
	
	/** 判断该路径是否以{@value #separatorChar}开头，如果不是，则添加{@value #separatorChar}符号 */
	public static String startWithSeparator(String path){
		if(path.charAt(0) != separatorChar){
			return separatorChar + path;
		}
		return path;
	}
	
	public static File generateFolder(String path) throws Exception{
		File folder = new File(path);
		if(!folder.isDirectory()){
			folder.mkdirs();
		}
		return folder;
	}

	public static String getFilename(String filepath) {
		String path = filepath;
		int sp = path.indexOf(separatorChar);
		if(sp >= 0)path = path.substring(sp + 1);
		int ep = path.lastIndexOf('.');
		if(ep > 0) path.substring(0, ep);
		return path;
	}
}
